package org.brisling.satisfaction.queryService;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.brisling.base.domain.ListDomain;
import org.brisling.base.service.AbstractBaseQueryService;
import org.brisling.common.ConstSysParam;
import org.brisling.common.exception.DangerousOperatorException;
import org.brisling.common.util.DateUtil;
import org.brisling.satisfaction.domain.SatisEvaluate;
import org.brisling.satisfaction.domain.SatisEvaluateHis;
import org.brisling.satisfaction.domain.SatisRank;
import org.brisling.satisfaction.domain.VOQuestion;
import org.brisling.satisfaction.domain.VOSatisfactionWindow;
import org.brisling.satisfaction.service.SatisRankService;
import org.brisling.sysman.queryService.QueryDictionaryService;
import org.brisling.sysman.queryService.QueryPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

@RestController
@RequestMapping("/satisEvaluateHis/query")
public class QuerySatisEvaluateHisService extends AbstractBaseQueryService<SatisEvaluateHis>{
	
	
	@Autowired
	private QueryDictionaryService dicService;
	@Autowired
	private SatisRankService srService;
	
	@Autowired
	private QueryPermissionService qryPermissionService;
	
	public QuerySatisEvaluateHisService(){
		this.moduleName = ConstSysParam.MODULE_SATISFACTIONHIS_EVALUATE;
		this.subSystem = ConstSysParam.SUBSYSTEM_STATISFACTION;
		this.tableName = "V_" +this.moduleName;
		this.clazz = SatisEvaluateHis.class;
		
		orderMap.put("pjsj","desc");	
	}
	
	@PersistenceContext(unitName=ConstSysParam.SUBSYSTEM_SYSMAN)
	@Autowired
	protected void setEntityManager(EntityManager entityManager){
		this.entityManager = entityManager;		
	}
	
	@RequestMapping("/mainPage.action")
	public ModelAndView getMainPage(){
		return this.getBizMainPage();
	}
	
	/* (non-Javadoc)
	 * @see org.brisling.service.sysman.DepartmentServiceInf#getEditPage()
	 */
	@RequestMapping("/editPage.action")
	public ModelAndView getEditPage(){
		return this.getBizEditPage();
	}	
	
	/**
	 * 门诊窗口满意度查询
	 * @return
	 */
	@RequestMapping("/windPage.action")
	public ModelAndView getWindowPage(){
		return new ModelAndView("/satisfaction/satisfaction_evaluate_his/window");
	}
	
	/**
	 * 门诊窗口满意度查询
	 * @return
	 */
	@RequestMapping("/popWindowPage.action")
	public ModelAndView getPopWindowPage(){
		return new ModelAndView("/satisfaction/satisfaction_evaluate_pop/popWindowMain");
	}
	
	/**
	 * 门诊问卷满意度查询
	 * @return
	 */
	@RequestMapping("/popSatisEvaluatePage.action")
	public ModelAndView getPopSatisEvaluatePage(){
		return new ModelAndView("/satisfaction/satisfaction_evaluate_pop/popOutpatientQuestion");
	}
	
	/**
	 * 住院科室满意度弹窗
	 * @return
	 */
	@RequestMapping("/popInpatientDeptPage.action")
	public ModelAndView getPopInpatientDeptPage(){
		return new ModelAndView("/satisfaction/satisfaction_evaluate_pop/popInpatientDept");
	}
	
	/**
	 * 住院问卷满意度弹窗
	 * @return
	 */
	@RequestMapping("/popInpatientQuestionPage.action")
	public ModelAndView getPopInpatientQuestionPage(){
		return new ModelAndView("/satisfaction/satisfaction_evaluate_pop/popInpatientQuestion");
	}
	
	/**
	 * 门诊窗口满意度查询
	 * @return
	 */
	@RequestMapping("/windowDetailPage.action")
	public ModelAndView getWindowDetailPage(){
		return new ModelAndView("/satisfaction/satisfaction_evaluate_his/windowDetail");
	}
	
	@SuppressWarnings("rawtypes")
	@RequestMapping("/getListDomain.action")
	public ListDomain<LinkedHashMap> getListDomain(@RequestParam(value="page",required=false) Integer page,
			@RequestParam(value="rows",required=false) Integer rows,
			@RequestParam(value="sort",required=false) String sort){		
		
		
		return super.getPagedListDomain(page, rows);
	}	
	
	@RequestMapping("/getTreeListDomain.action")
	public ListDomain<SatisEvaluateHis> getTreeListDomain(@RequestParam(value="id",required=false) Long id){
		
		return this.getPagedTreeListDomain(id);
		
	}	
	
	@RequestMapping("/getTreeList.action")
	public List<SatisEvaluateHis> getTreeList(@RequestParam(value="id",required=false) Long id){
		
		return this.getPagedTreeList(id);
		
	}	
	
	@RequestMapping("/getOne.action")
	public SatisEvaluateHis getOne(@RequestParam(value="id",required=false) Long id){
		return super.getOne(id);
	}
	
	
	/**
	 * 查询窗口满意度数据
	 * @param body
	 * @return
	 */
	
	@RequestMapping("/getWindowDomain.action")
	public ListDomain<Object> getWindowDomain(@RequestBody(required=false) String body){		
		
		String sql =dicService.getSqlByBizcode("satistic_window_his");		
		Map<String,Object> map = this.getTimeCondition(body);
		
		return 	super.getPagedClassListDomain(sql, map, SatisEvaluateHis.class, VOSatisfactionWindow.class,false);
		
	}
	
	/**
	 * 查询窗口满意度数据
	 * @param body
	 * @return
	 */
	
	@RequestMapping("/getWindowDetailDomain.action")
	public ListDomain<Object> getWindowDetailDomain(@RequestBody(required=false) String body){		
		
		String sql =dicService.getSqlByBizcode("satistic_window_detail_his");		
		Map<String,Object> map = this.getTimeCondition(body);
		
		return 	super.getPagedClassListDomain(sql, map, SatisEvaluate.class, VOSatisfactionWindow.class,false);
		
	}
	
	
	
	/**
	 * 获取评价时间条件
	 * @param body
	 * @return
	 */
	
	@SuppressWarnings("unchecked")
	private Map<String,Object> getTimeCondition(String body){
		Map<String,Object> map = this.getBodyParam(body);
		
		String[] dates = DateUtil.getMapMonthDay(map);
		if(dates!=null && dates.length>0 && dates[0]!=null){
			Map<String,String> paramMap = (Map<String, String>) map.get(ConstSysParam.CONDITION_MAP_KEY);	
			paramMap.put("pjsj_start", dates[0]);
			paramMap.put("pjsj_end", dates[1]);
			map.put(ConstSysParam.CONDITION_MAP_KEY, paramMap);
		}
		
		return map;
	}
	
	
	
	
	/**
	 * 自动生成质询纪录并发送
	 * @param userId 发送任务的用户ID
	 */
	
	public void autoSend(String userId, String bizcode, Date start_date, Date end_date)
	{
		
				
		List<SatisEvaluateHis> lists = this.getWindowUnSatisfy(bizcode, start_date, end_date); 
		
		
		if (lists != null)
		{
			System.out.println("-------------------------------------------------------------" + lists.size());
			for (SatisEvaluateHis e : lists)
			{
				SatisRank sr = this.satisEvaluateHisToSatisRank(e);
				//System.out.println("");
				srService.completeTask(userId, sr);
			}
		}
		else
		{
			System.out.println("-----------------------lists is null--------------------------------------");
		}
	}
	
	/**
	 * 自动生成质询纪录并发送
	 * @param userId 发送任务的用户ID
	 */
	
	public void autoSend(String userId, String bizcode, String start_date, String end_date)
	{
		
				
		List<SatisEvaluateHis> lists = this.getWindowUnSatisfy(bizcode, start_date, end_date); 
		
		
		if (lists != null)
		{
			System.out.println("-------------------------------------------------------------" + lists.size());
			for (SatisEvaluateHis e : lists)
			{
				SatisRank sr = this.satisEvaluateHisToSatisRank(e);
				//System.out.println("");
				srService.completeTask(userId, sr);
			}
		}
		else
		{
			System.out.println("-----------------------lists is null--------------------------------------");
		}
	}
	
	/**
	 * 查询窗口满意度异常数据
	 * @return 异常数据domain
	 */	
	public List<SatisEvaluateHis> getWindowUnSatisfy(String bizcode, Date start_date, Date end_date){	
		
		
		String sql = dicService.getSqlByBizcode(bizcode);		
		java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd");
		//sql = String.format(sql, format.format((new Date().getTime() - (long)24*60*60*1000)).toString());
		
		
		sql = String.format(sql, format.format(start_date.getTime() - (long) 24*60*60*1000).toString(), format.format(end_date.getTime()-(long) 24*60*60*1000).toString());
		
		try {
			return super.getClassedAllList(sql, SatisEvaluateHis.class);
		} catch (DangerousOperatorException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 查询窗口满意度异常数据
	 * @return 异常数据domain
	 */	
	public List<SatisEvaluateHis> getWindowUnSatisfy(String bizcode, String start_date, String end_date){	
		
		
		String sql = dicService.getSqlByBizcode(bizcode);		
		java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd");
		//sql = String.format(sql, format.format((new Date().getTime() - (long)24*60*60*1000)).toString());
		
		
		sql = String.format(sql, start_date,end_date);
		
		try {
			return super.getClassedAllList(sql, SatisEvaluateHis.class);
		} catch (DangerousOperatorException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	/**
	 * 由评价数据生成质询记录信息
	 * @param seh 评价数据
	 * @return sr 质询记录
	 */
	public SatisRank satisEvaluateHisToSatisRank(SatisEvaluateHis seh)
	{
		String fullBizCode = qryPermissionService.getBizFlowConfig("statisfactionInquiry").getFullBizcode();
		String flowId = qryPermissionService.getBizFlowConfig("statisfactionInquiry").getFlowid();
		String items[] = {"门诊窗口满意度异常", "门诊问卷满意度异常", "住院科室满意度异常", "住院问卷满意度异常"};
		SatisRank sr = new SatisRank();
		
		//根据评价ID可以查找详情
		if (seh.getPjid() != null) {
			sr.setEvaluate_id(seh.getPjid());
		}
		//责任部门	
		sr.setLitigant_deptid(Long.valueOf(seh.getDeptid()));
		sr.setLitigant_deptname(seh.getDepart_name());
		sr.setInquiry_date(Calendar.getInstance(TimeZone.getTimeZone("Asia/Shanghai")).getTime());
		sr.setInquiry_item_code(seh.getInquiry_item_code());
		sr.setFlowid(flowId);
		sr.setFullBizcode(fullBizCode);
		sr.setInquiry_reason(getReason(seh));
		sr.setInquiry_item(items[Integer.valueOf(seh.getInquiry_item_code())-37]);
		if (seh.getDoct_id() != null)
		{
			sr.setLitigant_id(Long.valueOf(seh.getDoct_id()));
		}
		if (seh.getDoct_name() != null)
		{
			sr.setLitigant_name(seh.getDoct_name());
		}
	
		System.out.println("\n----------------SatisRank-----start-------------------------------");
		System.out.println("fullbizcode=" + fullBizCode);
		System.out.println("flowId=" + flowId);
		System.out.println("deptid = " + sr.getLitigant_deptid() + " deptname = " + sr.getLitigant_deptname());
		System.out.println(" id = " + sr.getLitigant_id() + " name = " + sr.getLitigant_name());
		System.out.println(" Inquiry_item = " + sr.getInquiry_item() + " Inquiry_reason = " + sr.getInquiry_reason());
		System.out.println("----------------end-------------------------");
		return sr;
	}
	
	public String getReason(SatisEvaluateHis seh)
	{
		String result = "";
		if (seh.getBrbh() == null)
		{
			result += "匿名用户";
		}
		else
		{
			result += (seh.getBrxm() + "(" + seh.getBrbh() + ")");
		}
		if (seh.getScore() != null && seh.getScore().equals("1"))
		{
			result += (" 对" + seh.getDepart_name()); 
			if (Integer.valueOf(seh.getInquiry_item_code()) == 37 && seh.getDoct_name() != null && seh.getDoct_id() != null) {
				result += ("的" + seh.getDoct_name() + "(" + seh.getDoct_id() + ")");
			}  
			result += "非常不满意";
		}
		if (seh.getScore() != null && seh.getScore().equals("2"))
		{
			result += (" 对" + seh.getDepart_name()); 
			if (Integer.valueOf(seh.getInquiry_item_code()) == 37 && seh.getDoct_name() != null && seh.getDoct_id() != null) {
				result += ("的" + seh.getDoct_name() + "(" + seh.getDoct_id() + ")");
			} 
			result += "不满意";
		}
		java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time = format.format(seh.getPjsj());
		result += (" 评价时间: " + time);
		return result;
	}
	
	
	/**
	 * 根据评价ID获取题目
	 */
	@RequestMapping("/getSatisRankDetail.action")
	public List<VOQuestion> getSatisRankDetail(@RequestParam(value="evaluate_id",required=false) String evaluate_id){
		if (evaluate_id == null || evaluate_id.length() == 0) {
			return new ArrayList<VOQuestion>();
		}
 		String sql = "select * from V_SATIS_QUESTION_PROBLEM WHERE evaluate_id = to_char(%1$s)";
		sql = String.format(sql, evaluate_id);
		try {
			return super.getClassedAllList(sql, VOQuestion.class);
		} catch (DangerousOperatorException e) {
			e.printStackTrace();
		}
		return new ArrayList<VOQuestion>();
	}

}

